<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2024/3/13
 * Time: 15:54
 */

namespace app\admin\controller;

use think\Db;
use think\Request;

class Order extends Base
{
    /**
     * 订单首页
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $order_number = input('order_number');
            $is_pay = input('is_pay');
            $order_status = input('order_status');
            $userName = input('userName');
            $startTime = input('startTime');
            $endTime = input('endTime');

            $where = [];
            if($order_number) $where['order_number'] = ['LIKE', '%' . $order_number . '%'];
            if($userName) $where['user_xing|user_name'] = ['LIKE', '%' . $userName . '%'];
            if($is_pay) $where['order_is_pay'] = ['LIKE', '%' . $is_pay . '%'];
            if($order_status) $where['order_status'] = ['LIKE', '%' . $order_status . '%'];
            if($startTime && $endTime){
                $where['order_time'] = ['BETWEEN', [$startTime, $endTime]];
            }elseif ($startTime && !$endTime){
                $where['order_time'] = ['>', $startTime];
            }elseif (!$startTime && $endTime){
                $where['order_time'] = ['<', $endTime];
            }

            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_order')
                ->join('up_u_user', 'order_user_id = user_id', 'LEFT')
                ->join('up_address', 'addr_id = order_addr_id', 'LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_order')
                ->join('up_u_user', 'order_user_id = user_id', 'LEFT')
                ->join('up_address', 'addr_id = order_addr_id', 'LEFT')
                ->where($where)
                ->field([
                    'order_id',
                    'order_number',
                    'order_quantity',
                    'order_total_price',
                    'order_is_pay',
                    'order_status',
                    'order_time',
                    'user_xing',
                    'user_name'
                ])
                ->page($Nowpage, $limits)
                ->order('order_status ASC, order_time desc')
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }

    /**
     * 订单详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderDetail(){
        $order_id = input('order_id');
        $order = Db::table('up_order')
            ->join('up_u_user', 'user_id = order_user_id', 'LEFT')
            ->join('up_address', 'order_addr_id = addr_id', 'LEFT')
            ->where('order_id', $order_id)
            ->field([
                'order_number',
                'order_quantity',
                'order_total_price',
                'order_is_pay',
                'order_status',
                'order_wuLiu_company',
                'order_wuLiu_code',
                'order_wuLiu_desc',
                'order_time',
                'order_verify_time',
                'order_pay_time',
                'order_send_time',
                'order_over_time',
                'order_cancel_time',
                'user_xing',
                'user_name',
                'user_phone',
                'user_company',
                'user_position',
                'user_email',
                'addr_xing',
                'addr_name',
                'addr_phone',
                'addr_postal',
                'addr_company',
                'addr_address'
            ])
            ->find();

        return $this->fetch('', ['order' => $order]);
    }

    /**
     * 订单产品
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderGoods(){
        if(Request::instance()->isAjax()){
            $where['of_order_id'] = session('order_id');

            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_order_info')
                ->join('up_goods', 'of_goods_id = goods_id', 'LEFT')
                ->join('up_goods_packaging', 'packaging_id = of_packaging_id', 'LEFT')
                ->join('up_goods_spec', 'spec_id = of_spec_id', 'LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_order_info')
                ->join('up_goods', 'of_goods_id = goods_id', 'LEFT')
                ->join('up_goods_packaging', 'packaging_id = of_packaging_id', 'LEFT')
                ->join('up_goods_spec', 'spec_id = of_spec_id', 'LEFT')
                ->where($where)
                ->field([
                    'of_quantity',
                    'of_price',
                    'of_total_price',
                    'goods_name_en',
                    'spec_value',
                    'goods_spec_name_en',
                    'packaging_name',
                    'goods_thumb'
                ])
                ->order('of_id asc')
                ->page($Nowpage,$limits)
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $order_id = input('order_id');
        if(isset($order_id) && $order_id != ''){
            session('order_id', $order_id);
        }
        $addr = Db::table('up_order')
            ->join('up_address', 'order_addr_id = addr_id', 'LEFT')
            ->where('order_id', $order_id)
            ->field([
                'addr_xing',
                'addr_name',
                'addr_phone',
                'addr_postal',
                'addr_company',
                'addr_address',
                'order_quantity',
                'order_total_price'
            ])
            ->find();
        return $this->fetch('', ['addr' => $addr]);
    }

    /**
     * 已收款
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function alreadyPay(){
        $order_id = input('id');
        $order = Db::table('up_order')->where('order_id', $order_id)->field('order_status, order_is_pay')->find();
        if($order['order_is_pay'] == 2 || $order['order_status'] > 2){
            return json(['code' => 100, 'msg' => '订单状态异常，请刷新列表']);
        }

        $update = [
            'order_is_pay' => 2,
            'order_status' => 3,
            'order_pay_time' => initTime()
        ];
        $res = Db::table('up_order')->where('order_id', $order_id)->update($update);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }

    /**
     * 发货
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function sendOrder(){
        $order_id = input('order_id');
        if(Request::instance()->isPost()){
            $wuLiu_company = input('wuLiu_company');
            $wuLiu_code = input('wuLiu_code');
            $wuLiu_desc = input('wuLiu_desc');

            $update = [
                'order_wuLiu_company' => $wuLiu_company,
                'order_wuLiu_code' => $wuLiu_code,
                'order_wuLiu_desc' => $wuLiu_desc,
                'order_status' => 4,
                'order_send_time' => initTime()
            ];
            $res = Db::table('up_order')->where('order_id', $order_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        return $this->fetch('', ['order_id' => $order_id]);
    }

    /**
     * 物流
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function wuLiu(){
        $order_id = input('order_id');
        if(Request::instance()->isPost()){
            $wuLiu_company = input('wuLiu_company');
            $wuLiu_code = input('wuLiu_code');
            $wuLiu_desc = input('wuLiu_desc');

            $update = [
                'order_wuLiu_company' => $wuLiu_company,
                'order_wuLiu_code' => $wuLiu_code,
                'order_wuLiu_desc' => $wuLiu_desc,
                'order_update_time' => initTime()
            ];
            $res = Db::table('up_order')->where('order_id', $order_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        $wuLiu = Db::table('up_order')->where('order_id', $order_id)->field('order_wuLiu_company, order_wuLiu_code, order_wuLiu_desc')->find();
        return $this->fetch('', ['order_id' => $order_id, 'wl' => $wuLiu]);
    }

    /**
     * 导出
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function outExcel(){
        set_time_limit(0);
        $ids = input('ids');

        $where = [];
        if($ids == -1){
            $order_number = input('order_number');
            $is_pay = input('is_pay');
            $order_status = input('order_status');
            $userName = input('userName');
            $startTime = input('startTime');
            $endTime = input('endTime');

            if($order_number) $where['order_number'] = ['LIKE', '%' . $order_number . '%'];
            if($userName) $where['user_xing|user_name'] = ['LIKE', '%' . $userName . '%'];
            if($is_pay) $where['order_is_pay'] = ['LIKE', '%' . $is_pay . '%'];
            if($order_status) $where['order_status'] = ['LIKE', '%' . $order_status . '%'];
            if($startTime && $endTime){
                $where['order_time'] = ['BETWEEN', [$startTime, $endTime]];
            }elseif ($startTime && !$endTime){
                $where['order_time'] = ['>', $startTime];
            }elseif (!$startTime && $endTime){
                $where['order_time'] = ['<', $endTime];
            }
        }else{
            if($ids == ''){
                return json(['code' => 100, 'msg' => '请选择需要导出的数据']);
            }
            $where['order_id'] = ['IN', $ids];
        }

        $order = Db::table('up_order')
            ->join('up_u_user', 'order_user_id = user_id', 'LEFT')
            ->join('up_address', 'addr_id = order_addr_id', 'LEFT')
            ->where($where)
            ->field([
                'order_id',
                'order_number',
                'order_quantity',
                'order_total_price',
                'order_is_pay',
                'order_status',
                'order_time',
                'user_xing',
                'user_name',
                'addr_xing',
                'addr_name',
                'addr_phone',
                'addr_postal',
                'addr_company',
                'addr_address',
                'order_wuLiu_company',
                'order_wuLiu_code',
                'order_wuLiu_desc',
                'order_verify_time',
                'order_pay_time',
                'order_send_time',
                'order_over_time',
                'order_cancel_time'
            ])
            ->order('order_status ASC, order_time desc')
            ->select();

        if($order){
            $orderIds = array_column($order, 'order_id');
            $orderInfo = Db::table('up_order_info')
                ->join('up_goods', 'goods_id = of_goods_id', 'LEFT')
                ->join('up_goods_packaging', 'packaging_id = of_packaging_id', 'LEFT')
                ->join('up_goods_spec', 'spec_id = of_spec_id', 'LEFT')
                ->where('of_order_id', 'IN', $orderIds)
                ->field([
                    'of_order_id',
                    'of_quantity',
                    'of_price',
                    'of_total_price',
                    'goods_name_en',
                    'spec_value',
                    'goods_spec_name_en',
                    'packaging_name'
                ])
                ->select();
            foreach ($order as $k => $v){
                // 订单编号
                $order[$k]['order_number'] = "\t" . $v['order_number'] . "\t";
                // 支付状态
                $order[$k]['order_is_pay'] = $v['order_is_pay'] == 1 ? '未支付' : '已支付';

                // 订单状态
                switch ($v['order_status']){
                    case 1:
                        $order_status = '待确认';
                        break;
                    case 2:
                        $order_status = '待付款';
                        break;
                    case 3:
                        $order_status = '待发货';
                        break;
                    case 4:
                        $order_status = '待收货';
                        break;
                    case 5:
                        $order_status = '已收货';
                        break;
                    case 6:
                        $order_status = '已取消';
                        break;
                    default:
                        $order_status = '未知';
                }
                $order[$k]['order_status'] = $order_status;

                // 产品
                $str = '';
                foreach ($orderInfo as $ki => $vi){
                    if($vi['of_order_id'] == $v['order_id']){
                        $str .= '产品：' . $vi['goods_name_en'];
                        $str .= '_数量：' . $vi['of_quantity'];
                        $str .= '_单价：' . $vi['of_price'];
                        $str .= '_规格名：' . $vi['goods_spec_name_en'];
                        $str .= '_规格值：' . $vi['spec_value'];
                        $str .= '_包装：' . $vi['packaging_name'];
                        $str .= "\n";
                    }
                }
                $order[$k]['goods'] = $str;
            }

            $cellName = [
                ['order_id', '订单ID', 10, 'LEFT'],
                ['order_number', '订单编号', 20, 'LEFT'],
                ['order_quantity', '订单总数', 15, 'LEFT'],
                ['order_total_price', '订单总价', 15, 'LEFT'],
                ['order_status', '订单状态', 15, 'LEFT'],
                ['order_is_pay', '支付状态', 15, 'LEFT'],
                ['user_xing', '提交人_姓', 15, 'LEFT'],
                ['user_name', '提交人_名', 15, 'LEFT'],
                ['goods', '产品', 60, 'LEFT'],
                ['addr_xing', '收货联系人_姓', 16, 'LEFT'],
                ['addr_name', '收货联系人_名', 16, 'LEFT'],
                ['addr_phone', '收货联系方式', 15, 'LEFT'],
                ['addr_company', '收货人公司', 15, 'LEFT'],
                ['addr_postal', '收货人职务', 15, 'LEFT'],
                ['addr_address', '详细收货地址', 28, 'LEFT'],
                ['user_name', '物流公司', 15, 'LEFT'],
                ['user_name', '物流单号', 15, 'LEFT'],
                ['user_name', '物流描述', 15, 'LEFT'],
                ['order_time', '下单时间', 20, 'LEFT'],
                ['order_verify_time', '确认时间', 20, 'LEFT'],
                ['order_pay_time', '付款时间', 20, 'LEFT'],
                ['order_send_time', '发货时间', 20, 'LEFT'],
                ['order_over_time', '收货时间', 20, 'LEFT'],
                ['order_cancel_time', '取消时间', 20, 'LEFT'],
            ];
            $res = exportExcelZhy('订单', 'Order', $cellName, $order);
            return json($res);
        }else{
            return json(['code' => 100, 'msg' => '暂无可导出数据']);
        }
    }
}